package com.xzcedu.homework;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.Properties;

/**
 * @author 徐州城
 * @version 1.0
 * 1. 要编写一个dog.properties
 * name=tom
 * age=5
 * color=red
 * 2. 编写Dog 类(name, age, color) 创建一个dog对象，
 * 读取dog.properties 用相应的内容完成属性初始化，并输出
 * 3. 将创建的Dog 对象，序列化到文件 dog.dat文件
 */
public class Homework03 {
    public static void main(String[] args) throws IOException {

        //创建properties 对象
        Properties properties = new Properties();
        //修改
        properties.setProperty("name", "ton");
        properties.setProperty("age", "5");
        properties.setProperty("color", "red");

        properties.store(new FileWriter("e:\\ideaProject\\chapter18\\src\\com\\xzcedu\\homework\\dog.properties"), "Zhis is dog properties");

        //创建Dog对象 并初始化
        int age = Integer.parseInt(properties.getProperty("age"));//把String 转换为 int
        Dog dog = new Dog(properties.getProperty("name"), age, properties.getProperty("color"));
        System.out.println("Dog=" + dog);

        //对dog对象进行 序列化
        String fileName = "e:\\dog.dat";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(fileName));

//        objectOutputStream.writeUTF(dog.getName());
//        objectOutputStream.writeInt(dog.getAge());
//        objectOutputStream.writeUTF(dog.getColor());
        objectOutputStream.writeObject(dog);

        objectOutputStream.close();

        System.out.println("dog 对象，序列化完成...");
    }

    //编写一个方法，反序列化
    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String fileName = "e:\\dog.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));

        System.out.println(ois.readObject());

        ois.close();
    }
}

class Dog implements Serializable {//演示类 就写一些基本的属性
    private String name;
    private int age;
    private String color;

    public Dog(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}
